<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="fragment :: header('图片压缩')" />
</head>
<body>
    <div class="layui-form"> <!-- 提示：如果你不想用form，你可以换成div等任何一个普通元素 -->
        <div class="layui-form-item">
            <label class="layui-form-label">上传图片</label>
            <div class="layui-input-block">
                <button type="button" class="layui-btn" id="test1">
                    <i class="layui-icon">&#xe67c;</i>上传图片
                </button>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">原图</label>
            <div class="layui-input-block" id="img">

            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">按像素压缩</label>
            <div class="layui-input-block" id="compressByPixel">

            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">按大小压缩</label>
            <div class="layui-input-block" id="compressBySize">

            </div>
        </div>
    </div>
    <div id="previewLayer" style="display: none;padding:10px;">
        <img src="" id="previewImg" style="max-width: 100%;">
    </div>
    <th:block th:include="fragment :: footer" />
    <script>
        var fileList = [];
        layui.use('upload', function(){
            var upload = layui.upload;

            //执行实例
            var uploadInst = upload.render({
                elem: '#test1' //绑定元素
                ,url: ctx + '/img/compress/uploadAndCompress' //上传接口
                ,before: function(obj){ //obj参数包含的信息，跟 choose回调完全一致，可参见上文。
                    layer.load(); //上传loading
                }
                ,done: function(res){
                    layer.closeAll('loading'); //关闭loading
                    //上传完毕回调
                    if (res.code == 0) {
                        layer.msg('上传并压缩成功');
                        $("#img").html("<img src='"+ctx+res.imgs["原图"]+"' style='max-width: 500px;'>")
                        $("#compressByPixel").html("<img src='"+ctx+res.imgs["按像素压缩"]+"' style='max-width: 500px;'>")
                        $("#compressBySize").html("<img src='"+ctx+res.imgs["按大小压缩"]+"' style='max-width: 500px;'>")
                    } else {
                        if (res.msg) {
                            layer.msg(res.msg);
                        } else {
                            layer.msg('上传失败');
                        }
                    }

                }
                ,error: function(){
                    layer.closeAll('loading'); //关闭loading
                    //请求异常回调
                    layer.msg('出错了');
                }
            });
        });
    </script>
</body>
</html>